package com.base.invoke.okhttp.util;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 类反射工具
 * @author coolpig
 * @date 2019-08-28
 */
public class ClassUtils {
	/**
	 * 
	 * @param obj
	 * @return
	 */
	public static Map<String, String> objToMap(Object obj){
		Map<String, String> resMap = new HashMap<String, String>();
        List<Field> fields=ClassUtils.getFieldInfos(obj.getClass());
        for (Field f : fields) {
        		int mod = f.getModifiers();
            if(Modifier.isStatic(mod) || Modifier.isFinal(mod)){    
                continue;    
            }    
            f.setAccessible(true);
            try {
            	Object o = f.get(obj);
                if(o!=null) {
					resMap.put(f.getName(), o.toString());
                }
			} catch (Exception e) {
				throw new RuntimeException(e.getMessage(),e);
			}
		}
        return resMap;
    }
	/**
	 * 
	 * @param clazz
	 * @return
	 */
	public static List<Field> getFieldInfos(Class<?> clazz) {
		List<Field> fieldList = new ArrayList<>();
		Set<String> filedNameSet = new HashSet<>();
		for (Class<?> c = clazz; c != Object.class; c = c.getSuperclass()) {
			try {
				Field[] list = c.getDeclaredFields();
				for (Field f : list) {
					String name = f.getName();
					if (filedNameSet.contains(name)) {
						continue;
					}
					filedNameSet.add(f.getName());
					fieldList.add(f);
				}
			} catch (Exception e) {
				throw new RuntimeException(e.getMessage(),e);
			}
		}
		return fieldList;
	}
}
